<?php
/**
 * Selection
 *
 * Обработка данных подборок
 *
 * @author Mike
 */
class Selection extends ActiveRecord  {
	protected $tableName = 'selection';
	public $pkName = 'ID_selection';

	protected $arrSettings = array('created_at' => true);
	
	public $validatesLengthOf = array(
			'selection_name' => array('min' => 2, 'max' => 256, 'message' => 'Название - 2-256 символов'),
			'selection_page_name' => array('min' => 2, 'max' => 256, 'message' => 'Название для страницы - 2-256 символов'),
			'meta_description' => array('min' => 2, 'max' => 400, 'message' => 'Meta description - 2-400 символов','allowNull' => true),
			'meta_keywords' => array('min' => 2, 'max' => 400, 'message' => 'Meta keywords - 2-400 символов', 'allowNull' => true)
	);
	
	public $validatesFormatOf = array(
			'url' => array('with' => '/^[\-_a-z0-9\.]+$/ui', 'message' => 'URL заполнен неверно', 'allowNull' => true)
	);
	
	public $validatesUniquenessOf = array(
			'url' => array('message' => 'Такой URL уже используется')
	);
	
	public function beforeSave() {
		if(!isset($this->tableFields['is_main'])) $this->tableFields['is_main'] = 0;
		else $this->tableFields['is_main'] = 1;
	}
	
	/**
	 * Возвращает список подборок с товарами для каждой
	 * 
	 */
	public static function getAllSelections() {
		$objDB = Service_Database::instanse();
		$stmt = "SELECT *
				FROM `selection`
				LEFT JOIN `product_selection` USING(`ID_selection`)
				LEFT JOIN `product` USING(`ID_product`)";
		
		$arrSelections = $objDB->select($stmt);
		return Service_ArrayConverter::splitArrayByFields($arrSelections, array('ID_selection'));
	}
	
	/**
	 * Получает все товары текущей подборки
	 */
	public function getProducts() {
		$objDB = Service_Database::instanse();
		$stmt = "SELECT `product`.`product_name`, `product`.`url`, `product`.`ID_product`
				FROM `product_selection`
				INNER JOIN `product` USING(`ID_product`)
				WHERE `product_selection`.`ID_selection` = '" . $this->id . "'
				ORDER BY 1";
						
		return $objDB->select($stmt);
	}
}